<template>
  <base-breadcrumb class="UpdateArchiveApply-container" :title="breadcrumbTitle" :breadcrumb="!isAudit">
    <a-spin :spinning="loadingState.isBase">
      <a-card :bordered="false">
        <title-name title="项目基本信息" />
        <custom-form ref="baseInfoForm" :isValidate="true" editModel="V" :form="baseInfo" :formList="baseInfoList" />
      </a-card>
    </a-spin>
    <a-spin :spinning="loadingState.isDetail">
      <a-card :bordered="false">
        <title-name title="归档资料" />
        <custom-form
          ref="ruleForm"
          :isValidate="true"
          :editModel="isDisabled ? 'V' : ''"
          :rules="rules"
          :form="formInfo"
          :formList="formItemList"
        >
          <template v-for="fileItem in formItemList" v-slot:[fileItem.keyName]>
            <template v-if="!isDisabled">
              <l-table
                :fileAutoLoading="false"
                businessCode="ARC02"
                :uploadArrys.sync="formInfo[fileItem.keyName]"
                :useAccept="true"
                :accept="'.rar,.zip,.doc,.docx,.pdf,.jpg,.png'"
              ></l-table>
            </template>
            <file-link v-else :fileList="formInfo[fileItem.keyName]"></file-link>
          </template>
        </custom-form>
        <div class="file-tips">支持格式：.rar .zip .doc .docx .pdf .jpg .png</div>
      </a-card>
    </a-spin>
    <div v-if="!isConsultation" class="tool-btns page-btn-right-top">
      <a-button v-if="!isDisabled" type="primary" :loading="loadingState.DRAFT" @click="handleSubmit('DRAFT')"
        >保存草稿</a-button
      >
      <a-button
        v-if="!isDisabled"
        class="ml12"
        type="primary"
        :loading="loadingState.SUBMITTED"
        @click="handleSubmit('SUBMITTED')"
        >提交</a-button>
      <a-button class="ml12" type="default" @click="handleClose">关闭</a-button>
    </div>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { batchArchiveDoc, getBatchArchiveDoc, getProjectByArchive } from '@/api/office/archiveManage/archiveDoc.js'
import Vue from 'vue'
import { getProjectsDel } from '@/api/project/projects'
import { getInfoByStaffId } from '@/api/commons.js'

export default {
  name:'a'+Date.now(),
  props: {
      // 是否作为审批详情
      isAudit: {
        type: Boolean,
        default: false
      },
      // 是否作为意见征询
      isConsultation: {
        type: Boolean,
        default: false
      }
    },
  data() {
    return {
      loadingState: {
        isBase: false,
        isDetail: false,
        DRAFT: false,
        SUBMITTED: false,
      },
      projectInfo: {},
      formInfo: {},
      rules: {},
      baseInfo: {},
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  computed: {
    pageType() {
      if (this.isAudit) {
        return 'look'
      }
      return this.$route.query.pageType || 'look'
    },
    breadcrumbTitle() {
      const map = {
        add: '项目竣工归档新增',
        edit: '项目竣工归档编辑',
        look: '项目竣工归档详情',
      }
      return map[this.pageType] || map['look']
    },
    isDisabled() {
      return this.pageType === 'look'
    },
    baseInfoList() {
      return [
      {
          label: '所属单位',
          keyName: 'affiliatedUnit',
          type: 'BaseInput',
          disabled: true,
        },
        // {
        //   label: '分公司',
        //   keyName: 'implementationThreeName',
        //   type: 'BaseInput',
        //   disabled: true,
        // },
        // {
        //   label: '项目名称',
        //   keyName: 'projectName',
        //   type: 'BaseInput',
        //   disabled: true,
        // },
        {
          label: '建筑面积',
          keyName: 'contractTotalArea',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '结构类型',
          keyName: 'structureTypeName',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '合同金额（万元）',
          keyName: 'contractValue',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '项目经理',
          keyName: 'realityPmName',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '联系电话',
          keyName: 'phone',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '开工时间',
          keyName: 'contractStartDate',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '计划竣工时间',
          keyName: 'contractEndDate',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '计划归档日期',
          keyName: 'archiveTime',
          type: 'BaseInput',
          disabled: true,
        },
      ]
    },
    formItemList() {
      return [
        {
          slot: true,
          keyName: 'file-0',
          label: '中标通知',
          codeType: 0,
          isRequired: true,
        },
        {
          slot: true,
          keyName: 'file-1',
          label: '合同',
          codeType: 1,
          isRequired: true,
        },
        {
          slot: true,
          keyName: 'file-2',
          label: '开工报告',
          codeType: 2,
          isRequired: true,
        },
        {
          slot: true,
          keyName: 'file-3',
          label: '竣工报告',
          codeType: 3,
          isRequired: true,
        },
        {
          slot: true,
          keyName: 'file-4',
          label: '（预）决算档案',
          codeType: 4,
          isRequired: false,
        },
        {
          slot: true,
          keyName: 'file-5',
          label: '工程档案三级目录',
          codeType: 5,
          isRequired: true,
        },
        {
          slot: true,
          keyName: 'file-6',
          label: '档案系统已录入截图',
          codeType: 6,
          isRequired: true,
          span: 24,
        },
      ]
    },
  },
 async created() {
    this.getProjectsDelReq()
    this.getBatchArchiveDocReq()
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('completion_data_archive')
  },
  methods: {
    /**
     * 获取已上传附件列表
     */
    async getBatchArchiveDocReq() {
      try {
        if (!this.$route.query.id) return
        this.loadingState.isDetail = true
        const params = {
          archiveInfoId: this.$route.query.id,
        }
        const res = await getBatchArchiveDoc(params)
        // 根据不同的type值，获取不同的附件
        this.formItemList.forEach((formItem) => {
          const targetList = res.data.filter((item) => item.type === formItem.codeType)
          targetList.forEach((item) => {
            if (!this.formInfo[`file-${item.type}`]) {
              this.$set(this.formInfo, `file-${item.type}`, [])
            }
            this.formInfo[`file-${item.type}`].push(item.fileInfoVO)
          })
        })
        this.loadingState.isDetail = false
      } catch (e) {
        console.error(e)
        this.loadingState.isDetail = false
      }
    },
    async getProjectsDelReq() {
      try {
        this.loadingState.isBase = true
        this.baseInfo.archiveTime = this.$route.query.archiveTime
        let projectId = this.$route.query.projectId
        let archiveRes = {}
        if(this.$route.query.id) {
          archiveRes = await getProjectByArchive({id: this.$route.query.id})
          projectId = archiveRes.data.projectId
          this.baseInfo.archiveTime = archiveRes.data.archiveTime
          
        }
        const res = await getProjectsDel({ projectId: projectId })
        const delRes = await getInfoByStaffId(res.data?.realityPmId)
        this.baseInfo = {
          ...this.baseInfo,
          ...res.data,
          phone: delRes?.data?.phoneNum,
          affiliatedUnit: archiveRes.data.branchOrgName+'/'+res.data.projectOmit
        }
        this.loadingState.isBase = false
      } catch (e) {
        console.error(e)
        this.loadingState.isBase = false
      }
    },
    /**
     * 保存草稿、提交等操作
     * @param {String} actionName 'DRAFT': 保存草稿  'SUBMITTED'：提交
     */
    handleSubmit(actionName) {
      const fileList = []
      this.formItemList.forEach((item) => {
        if (item.isRequired && actionName === 'SUBMITTED' && !this.formInfo[item.keyName]?.length) {
          this.$message.warning(`请上传${item.label}`)
          throw new Error('break')
        }
        const targetFileList = this.formInfo[item.keyName]
        targetFileList &&
          targetFileList.forEach &&
          targetFileList.forEach((targetItem) => {
            fileList.push({
              fileId: targetItem.commonId,
              type: item.codeType,
            })
          })
      })
      if (actionName === 'SUBMITTED') {
        this.$refs.ruleForm.validate((valid) => {
          if (!valid) {
            this.$message.warning("请填写完所有必填项信息")
            return
          }
          this.invokeSave(actionName, fileList)
        })
      } else {
        this.invokeSave(actionName, fileList)
      }
    },
    /**
     * 保存接口调用
     */
    async invokeSave(actionName, fileList = []) {
      this.setProcessConfig = null;
      if (this.loadingState[actionName]) return
      try {
        this.loadingState[actionName] = true
        const params = {
          archiveDataStatus: actionName,
          archiveInfoId: this.$route.query.id,
          fileList,
        }
        await batchArchiveDoc(params)
        this.loadingState[actionName] = false
        this.$message.success(actionName === 'DRAFT' ? '保存成功' : '提交成功')
         if(actionName =='SUBMITTED') {
            //提交时，返回id
                this.businessId = this.$route.query.id;
                this.setProcessConfig = this.processConfig;
                return
            }else{
             this.$multiTab.close()
          }
      } catch (e) {
        console.error(e)
        this.loadingState[actionName] = false
      }
    },
    handleClose() {
      this.$close()
    },
  },
}
</script>

<style lang="less" scoped>
.file-tips {
  color: #999999;
  padding-left: 50px;
}
</style>
